import React, { useEffect, useRef, useState } from "react";
import Danmaku from "rc-danmaku"; // 导入 rc-danmaku
import "./index.css";
import { Input, Button } from "antd";
import { getRandomColor } from "../../utils/index";
import { filterSensitiveWords } from "../../utils/index";
type Props = {
  src: string;
};
const sensitiveWords = ["艹", "草",'操','傻逼','傻']; // 敏感词列表
const Index = ({ src }: Props) => {
  const danmakuInsRef = useRef<Danmaku | null>(null);
  const [danmakuText, setDanmakuText] = useState("");
  const [isInputShow, setIsInputShow] = useState(false);
  const sendmsg = () => {
    if (danmakuInsRef.current) {
      danmakuInsRef.current.push(
        filterSensitiveWords(danmakuText, sensitiveWords),
        {
          color: getRandomColor(),
        }
      );
      setDanmakuText("");
    }
  };
  const sendBarrage = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.key === "Enter") {
      sendmsg();
    }
  };

  useEffect(() => {
    const danmakuIns = new Danmaku(".danmaku-wrapper", {
      rowHeight: 40, // 弹幕轨道高度，默认40（单位px）
      speed: 120, // 弹幕速度，默认100（单位px/s）
      opacity: 0.7, // 弹幕透明度，默认为1，范围 0-1
      maxRow: 7, // 弹幕最大轨道数，会根据容器高度自动计算，也可以手动赋值
    });
    danmakuInsRef.current = danmakuIns;
    danmakuInsRef.current.push("我是小帅", { color: getRandomColor() });
    danmakuInsRef.current.push("主播主播", { color: getRandomColor() });
    danmakuInsRef.current.push("你会唱歌吗", { color: getRandomColor() });
    return () => {
      danmakuInsRef.current?.destroy();
    };
  }, []);

  return (
    <div
      className="danmaku-wrapper"
      onMouseOver={() => setIsInputShow(true)}
      onMouseLeave={() => setIsInputShow(false)}
    >
      <video
        className="myvideo"
        src={src}
        // 显示播放控制按钮
        controls
        // 自动播放
        autoPlay
        // 默认静音
        muted
        width="100%"
        onPause={() => danmakuInsRef.current?.pause()}
        onPlay={() => danmakuInsRef.current?.resume()}
      ></video>
      {isInputShow && (
        <div className="danmaku-input">
          <Input
            value={danmakuText}
            placeholder="请输入弹幕"
            onChange={(e) => setDanmakuText(e.target.value)}
            onKeyDown={sendBarrage}
          ></Input>
          &nbsp; &nbsp;
          <Button
            type="primary"
            onClick={() => {
              sendmsg();
            }}
          >
            发送
          </Button>
        </div>
      )}
    </div>
  );
};

export default Index;
